<html>
<head>

<title>Groovy Goodness: Setting a Closure's Delegate</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Setting a Closure's Delegate</h3>

<div class="post">
<p>Closures are reusable code blocks in Groovy. The code of the closure is executed against the delegate of the closure. By default the owner of the closure is the same as the delegate, but we can change this. We can define which object is the delegate for a closure, so we can change the object the closure is executed for.</p>
<pre class="brush:groovy">
// Simple class.
class Post {
    int count
    def info() { "This is Groovy Goodness post #$count!" }
}

// Script variable and method.
count = 0
def info() {
    "Count value is $count."
}

// Closure to increment a count variable and invoke a info() method.
def printInfo = { 
    count++
    info() 
}

assert "Count value is 1." == printInfo() // Delegate is by default set to owner, so the script in this case.

printInfo.resolveStrategy = Closure.DELEGATE_FIRST  // Change closure resolver so first the delegate is used.
printInfo.delegate = new Post(count: 100)  // Set delegate to Post object.
assert "This is Groovy Goodness post #101!" == printInfo()
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>